﻿using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Windows.Forms;
using EventScavenger;

namespace EventScavenger
{
    public partial class MainForm : Form
    {
        public MainForm()
        {
            InitializeComponent();
        }

        private EventScavengerDAL sqlEventSource = new EventScavengerDAL();
        
        #region Form events
        private void MainForm_Load(object sender, EventArgs e)
        {
            SetAppTitle();
            
            sqlEventSource.Server = Properties.Settings.Default.SQLServer;
            sqlEventSource.Database = Properties.Settings.Default.Database;
            sqlEventSource.UserName = Properties.Settings.Default.UserName;
            sqlEventSource.Password = Properties.Settings.Default.Password;
            sqlEventSource.SetConnection();

            DelayExecute.Execute(this, 1000, RefreshList);
        }
        #endregion

        #region Listview events
        private void lvwEventMachineLogs_SelectedIndexChanged(object sender, EventArgs e)
        {
            EnableMenus();
        }
        private void lvwEventMachineLogs_DoubleClick(object sender, EventArgs e)
        {
            EditEntry();
        }
        private void lvwEventMachineLogs_KeyUp(object sender, KeyEventArgs e)
        {
            if (e.KeyCode == Keys.Enter)
            {
                EditEntry();
            }
        }
        #endregion

        #region Menu events
        private void toolStripMenuItemAdd_Click(object sender, EventArgs e)
        {
            AddEntry();
        }
        private void bulkAddToolStripMenuItem_Click(object sender, EventArgs e)
        {
            BulkAdd();
        }
        private void edittoolStripMenuItem_Click(object sender, EventArgs e)
        {
            EditEntry();
        }
        private void deleteToolStripMenuItem_Click(object sender, EventArgs e)
        {
            if (MessageBox.Show("Are you absolutely sure you want to delete these event log(s) and all their data?\r\nThis operation can possibly take very long and is NOT reversible!", "Delete", MessageBoxButtons.YesNo, MessageBoxIcon.Question) == DialogResult.Yes)
            {
                try
                {
                    Cursor.Current = Cursors.WaitCursor;
                    foreach (ListViewItem lvi in lvwEventMachineLogs.SelectedItems)
                    {
                        MachineLogEntry mle = (MachineLogEntry)lvi.Tag;
                        toolStripStatusLabelRecords.Text = string.Format("Deleting {0}", mle.ToString());
                        Application.DoEvents();
                        Cursor.Current = Cursors.WaitCursor;
                        sqlEventSource.DeleteMachineLog(mle.MachineLogID);                        
                    }
                    RefreshList();
                }
                catch (Exception ex)
                {
                    MessageBox.Show(ex.Message, "Error", MessageBoxButtons.OK, MessageBoxIcon.Error);
                }
                finally
                {
                    Cursor.Current = Cursors.Default;
                }
            }
        }
        private void exitToolStripMenuItem_Click(object sender, EventArgs e)
        {
            Close();
        }
        private void refreshToolStripMenuItem_Click(object sender, EventArgs e)
        {
            RefreshList();
        }
        private void SetSort(bool name, bool lastUpdate, bool oldest, bool newest, bool count)
        {
            nameToolStripMenuItem.Checked = name;
            nameToolStripMenuItem1.Checked = name;
            lastUpdateDateToolStripMenuItem.Checked = lastUpdate;
            lastUpdateDateToolStripMenuItem1.Checked = lastUpdate;
            oldestEntryToolStripMenuItem.Checked = oldest;
            oldestEntryToolStripMenuItem1.Checked = oldest;
            newestEntryToolStripMenuItem.Checked = newest;
            newestEntryToolStripMenuItem1.Checked = newest;
            entryCountToolStripMenuItem.Checked = count;
            entryCountToolStripMenuItem1.Checked = count;
            RefreshList();
        }
        private void nameToolStripMenuItem_Click(object sender, EventArgs e)
        {
            SetSort(true, false, false, false, false);
        }
        private void lastUpdateDateToolStripMenuItem_Click(object sender, EventArgs e)
        {
            SetSort(false, true, false, false, false);
        }
        private void oldestEntryToolStripMenuItem_Click(object sender, EventArgs e)
        {
            SetSort(false, false, true, false, false);
        }
        private void newestEntryToolStripMenuItem_Click(object sender, EventArgs e)
        {
            SetSort(false, false, false, true, false);
        }
        private void entryCountToolStripMenuItem_Click(object sender, EventArgs e)
        {
            SetSort(false, false, false, false, true);
        }
        private void connectionToolStripMenuItem_Click(object sender, EventArgs e)
        {
            SetConnection setConnection = new SetConnection();
            if (setConnection.ShowSetConnection() == DialogResult.OK)
            {
                sqlEventSource.Server = Properties.Settings.Default.SQLServer;
                sqlEventSource.Database = Properties.Settings.Default.Database;
                sqlEventSource.UserName = Properties.Settings.Default.UserName;
                sqlEventSource.Password = Properties.Settings.Default.Password;
                sqlEventSource.SetConnection();
                SetAppTitle();
                RefreshList();
            }
        }
        private void toolStripButtonCurrentStatusses_Click(object sender, EventArgs e)
        {
            MachineLogStatusses machineLogStatusses = new MachineLogStatusses();
            machineLogStatusses.EventScavengerDAL = sqlEventSource;
            machineLogStatusses.Show();
        }
        private void globalSettingsToolStripMenuItem_Click(object sender, EventArgs e)
        {
            GlobalSettings globalSettings = new GlobalSettings();
            globalSettings.ShowSettings(sqlEventSource);
        }
        private void collectorsToolStripMenuItem_Click(object sender, EventArgs e)
        {
            Collectors collectors = new Collectors();
            collectors.Show(sqlEventSource);
        }
        private void pollingFiltersToolStripMenuItem_Click(object sender, EventArgs e)
        {
            PollingFilters pollingFilters = new PollingFilters();
            pollingFilters.Show(sqlEventSource);
        }
        private void importForeignLogsToolStripMenuItem_Click(object sender, EventArgs e)
        {
            ImportForeignLogs importForeignLogs = new ImportForeignLogs();
            importForeignLogs.Show(sqlEventSource);
        }
        private void aboutToolStripMenuItem_Click(object sender, EventArgs e)
        {
            AboutWindow aboutWindow = new AboutWindow();
            aboutWindow.ShowDialog();
        }
        #endregion

        #region Context Menu events
        private void enableToolStripMenuItem_Click(object sender, EventArgs e)
        {
            foreach (ListViewItem lvi in lvwEventMachineLogs.SelectedItems)
            {
                MachineLogEntry mle = (MachineLogEntry)lvi.Tag;
                mle.Enabled = true;
                sqlEventSource.UpdateMachineLogEntry(mle);
                lvi.Tag = mle;
                lvi.ForeColor = SystemColors.WindowText;
            }
            bool entryEnable = false;
            bool entryNotEnable = true;
            toolStripButtonEnable.Enabled = entryEnable;
            enableToolStripMenuItem.Enabled = entryEnable;
            toolStripButtonNotEnabled.Enabled = entryNotEnable;
            disableToolStripMenuItem.Enabled = entryNotEnable;
        }
        private void disableToolStripMenuItem_Click(object sender, EventArgs e)
        {
            foreach (ListViewItem lvi in lvwEventMachineLogs.SelectedItems)
            {
                MachineLogEntry mle = (MachineLogEntry)lvi.Tag;
                mle.Enabled = false;
                sqlEventSource.UpdateMachineLogEntry(mle);
                lvi.Tag = mle;
                lvi.ForeColor = Color.DarkGray;
            }
            bool entryEnable = true;
            bool entryNotEnable = false;
            toolStripButtonEnable.Enabled = entryEnable;
            enableToolStripMenuItem.Enabled = entryEnable;
            toolStripButtonNotEnabled.Enabled = entryNotEnable;
            disableToolStripMenuItem.Enabled = entryNotEnable;
        }
        #endregion
        
        #region Private methods
        private void SetAppTitle()
        {
            this.Text = "Event Scavenger Admin - " + Application.ProductVersion;
            if (Properties.Settings.Default.SQLServer.Length > 0)
            {
                this.Text += " - " + Properties.Settings.Default.SQLServer;
            }
        }
        private ListViewGroup GetListViewGroupByName(string name)
        {
            ListViewGroup group = null;
            foreach (ListViewGroup lvg in lvwEventMachineLogs.Groups)
            {
                if (lvg.Name.ToUpper() == name.ToUpper())
                {
                    group = lvg;
                    break;
                }
            }
            if (group == null)
            {
                group = new ListViewGroup(name.ToUpper(), name.ToUpper());
                lvwEventMachineLogs.Groups.Add(group);
            }
            return group;
        }
        private void RefreshList()
        {
            ListViewItem lvwi;
            MachineLogEntry mleSelected = null;
            List<MachineLogEntry> machineLogList;
            int totalCount = 0;
            if (lvwEventMachineLogs.SelectedItems.Count > 0)
            {
                mleSelected = (MachineLogEntry)lvwEventMachineLogs.SelectedItems[0].Tag;
            }
            Cursor.Current = Cursors.WaitCursor;
            toolStripButtonEnable.Enabled = false;
            enableToolStripMenuItem.Enabled = false;
            toolStripButtonNotEnabled.Enabled = false;
            disableToolStripMenuItem.Enabled = false;
            lvwEventMachineLogs.Items.Clear();
            try
            {
                lvwEventMachineLogs.BeginUpdate();
                Cursor.Current = Cursors.WaitCursor;
                machineLogList = sqlEventSource.GetMachineLogListAll();
                if (nameToolStripMenuItem.Checked)
                    machineLogList = (from me in machineLogList
                                      orderby me.Machine + "\\" + me.LogName
                                      select me).ToList();
                else if (lastUpdateDateToolStripMenuItem.Checked)
                    machineLogList = (from me in machineLogList
                                      orderby me.LastPollTime descending
                                      select me).ToList();
                else if (oldestEntryToolStripMenuItem.Checked)
                    machineLogList = (from me in machineLogList
                                      orderby me.OldestEntry
                                      select me).ToList();
                else if (newestEntryToolStripMenuItem.Checked)
                    machineLogList = (from me in machineLogList
                                      orderby me.NewestEntry descending
                                      select me).ToList();
                else // if (entryCountToolStripMenuItem.Checked)
                    machineLogList = (from me in machineLogList
                                      orderby me.EntryCount descending
                                      select me).ToList();
                List<ListViewItem> lvitems = new List<ListViewItem>();
                foreach (MachineLogEntry mle in machineLogList)
                {
                    lvwi = new ListViewItem(mle.Machine + "\\" + mle.LogName);
                    lvwi.Group = GetListViewGroupByName(mle.Collector);
                    if (!mle.Enabled)
                    {
                        lvwi.ForeColor = Color.DarkGray;
                    }
                    lvwi.SubItems.Add(mle.LastPollTime.ToString("yyyy-MM-dd HH:mm"));
                    lvwi.SubItems.Add(mle.PollFrequency.ToString());
                    //lvwi.SubItems.Add(mle.OldestEntry.ToString("yyyy-MM-dd HH:mm"));
                    //lvwi.SubItems.Add(mle.NewestEntry.ToString("yyyy-MM-dd HH:mm"));
                    //lvwi.SubItems.Add(mle.EntryCount.ToString());
                    totalCount += mle.EntryCount;
                    lvwi.Tag = mle;
                    lvitems.Add(lvwi);
                    

                    if ((mleSelected != null) && (mleSelected.MachineLogID == mle.MachineLogID))
                    {
                        lvwi.Selected = true;
                    }
                }
                lvwEventMachineLogs.Items.AddRange(lvitems.ToArray());
                toolStripStatusLabelLogCount.Text = lvwEventMachineLogs.Items.Count.ToString() + " log(s)";
                toolStripStatusLabelRecords.Text = totalCount.ToString() + " record(s)";
                EnableMenus();
            }
            catch (Exception ex)
            {
                MessageBox.Show(ex.ToString() + "\r\n" + sqlEventSource.LastError, "Error", MessageBoxButtons.OK, MessageBoxIcon.Error);
            }
            finally
            {
                lvwEventMachineLogs.EndUpdate();
                Cursor.Current = Cursors.Default;
                DelayExecute.Execute(this, 100, SetSelectedItemVisible);
            }
        }
        private void SetSelectedItemVisible()
        {
            if (lvwEventMachineLogs.SelectedItems.Count > 0)
                lvwEventMachineLogs.SelectedItems[0].EnsureVisible();
        }
        private void AddEntry()
        {
            MachineLogEntryEdit machineLogEntryEdit = new MachineLogEntryEdit();
            MachineLogEntry newEntry = new MachineLogEntry("", "");
            if (machineLogEntryEdit.ShowMachineLogEntry(sqlEventSource, newEntry) == DialogResult.OK)
            {
                RefreshList();
            }
        }
        private void BulkAdd()
        {
            BulkAddMachineLogs bulkAddMachineLogs = new BulkAddMachineLogs();
            if (bulkAddMachineLogs.ShowDialog(sqlEventSource) == DialogResult.OK)
            {
                RefreshList();
            }
        }
        private void EditEntry()
        {
            if (lvwEventMachineLogs.SelectedItems.Count > 0)
            {
                MachineLogEntry mle = (MachineLogEntry)lvwEventMachineLogs.SelectedItems[0].Tag;
                MachineLogEntryEdit machineLogEntryEdit = new MachineLogEntryEdit();
                if (machineLogEntryEdit.ShowMachineLogEntry(sqlEventSource, mle) == DialogResult.OK)
                {
                    mle = sqlEventSource.GetMachineLogEntry(mle.Machine, mle.LogName);
                    if (mle.MachineLogID > -1)
                    {
                        ListViewItem lvi = lvwEventMachineLogs.SelectedItems[0];
                        lvi.Group = GetListViewGroupByName(mle.Collector);
                        lvi.Tag = mle;
                        lvi.Checked = mle.Enabled;
                        lvi.SubItems[2].Text = mle.PollFrequency.ToString();
                        if (!mle.Enabled)
                        {
                            lvi.ForeColor = Color.DarkGray;
                        }
                        else
                            lvi.ForeColor = SystemColors.WindowText;
                    }
                    else
                    {
                        lvwEventMachineLogs.Items.Remove(lvwEventMachineLogs.SelectedItems[0]);
                    }
                }
            }
        }
        private void EnableMenus()
        {
            editToolStripButton.Enabled = (lvwEventMachineLogs.SelectedItems.Count == 1);
            editToolStripMenuItem1.Enabled = (lvwEventMachineLogs.SelectedItems.Count == 1);
            edittoolStripMenuItem.Enabled = (lvwEventMachineLogs.SelectedItems.Count == 1);
            deleteToolStripMenuItem.Enabled = (lvwEventMachineLogs.SelectedItems.Count > 0);
            deleteToolStripMenuItem1.Enabled = (lvwEventMachineLogs.SelectedItems.Count > 0);
            bool entryEnable = false;
            bool entryNotEnable = false;
            if (lvwEventMachineLogs.SelectedItems.Count > 0)
            {
                if (lvwEventMachineLogs.SelectedItems[0].ForeColor == Color.DarkGray)
                {
                    entryEnable = true;
                    entryNotEnable = false;
                }
                else
                {
                    entryEnable = false;
                    entryNotEnable = true;
                }
            }
            toolStripButtonEnable.Enabled = entryEnable;
            enableToolStripMenuItem.Enabled = entryEnable;
            toolStripButtonNotEnabled.Enabled = entryNotEnable;
            disableToolStripMenuItem.Enabled = entryNotEnable;
        }
        #endregion        

        

        

        

    }
}
